package org.springblade.modules.admin.task;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.lark.oapi.Client;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.config.FeiShuConfiguration;
import org.springblade.common.enums.FeishuClientEnum;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.entity.MaintainMsg;
import org.springblade.modules.admin.entity.UserCert;
import org.springblade.modules.admin.entity.feishu.FeiShuCertContentTemplate;
import org.springblade.modules.admin.enums.CertStatusEnum;
import org.springblade.modules.admin.enums.MsgTypeEnum;
import org.springblade.modules.admin.service.MaintainMsgService;
import org.springblade.modules.admin.service.UserCertService;
import org.springblade.modules.admin.vo.UserCertVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 证件相关定时任务
 * @Author ysq
 * @Date 2024/04/08
 **/
@Slf4j
@Component
public class CertJob {

	@Autowired
	private MaintainMsgService msgService;
	@Autowired
	private UserCertService userCertService;
	@Autowired
	private FeiShuConfiguration feiShuConfiguration;

	/**
	 * 人员证件更新状态任务
	 */
	@XxlJob(value = "updateUserCertStatus")
	public void updateUserCertStatus() {
		XxlJobHelper.log("人员证件更新状态任务-【执行】开始");
 		List<UserCert> updateList = new ArrayList<>();
		List<UserCertVO> list = userCertService.selectAllList();
		for (UserCertVO cert : list) {
			// 提醒日期
			Date reminderDate = DateUtil.offsetDay(cert.getEndTime(), -cert.getExpireIn());
			int diff = DateUtil.compare(reminderDate, DateUtil.date(), DatePattern.NORM_DATE_PATTERN);
			Integer status = null;
			if (diff > 0) {
				// 正常
				status = CertStatusEnum.NORMAL.getId();
			} else if (DateUtil.compare(DateUtil.date(), cert.getEndTime(), DatePattern.NORM_DATE_PATTERN) < 0) {
				// 即将到期
				status = CertStatusEnum.EXPIRING_SOON.getId();
			} else {
				// 已到期
				status = CertStatusEnum.EXPIRED.getId();
			}

			if (!Func.equalsSafe(status, cert.getStatus())) {
				UserCert userCert = new UserCert();
				userCert.setId(cert.getId());
				userCert.setStatus(status);
				updateList.add(userCert);
			}
		}
		userCertService.updateBatchById(updateList);
		XxlJobHelper.handleSuccess("人员证件更新状态任务-【执行】成功");
	}

	/**
	 * 证件到期提醒通知
	 */
	@XxlJob(value = "expiredReminder")
	public void certExpiredReminder() {
		XxlJobHelper.log("证件到期提醒任务-【执行】开始");
		List<MaintainMsg> msgList = new ArrayList<>(16);
		List<UserCertVO> list = userCertService.selectAllList();
		for (UserCertVO cert : list) {
			// 提醒日期
			Date reminderDate = DateUtil.offsetDay(cert.getEndTime(), -cert.getExpireIn());
			if (DateUtil.compare(reminderDate, DateUtil.date(), DatePattern.NORM_DATE_PATTERN) == 0) {
				// 通知内容
				String title = String.format("姓名：%s", cert.getRealName());
				String content = String.format("证件：【%s】即将到期", cert.getCertName());
				MaintainMsg msg = new MaintainMsg();
				msg.setTitle(title);
				msg.setContent(content);
				msg.setType(MsgTypeEnum.CERT_EXPIRED.getId());
				msg.setOtherId(cert.getId());
				msg.setCode("personPapers");
				msg.setTenantId(cert.getTenantId());
				msgList.add(msg);
			}
		}

		// 发送通知提醒
		if (Func.isNotEmpty(msgList)) {
			// 系统消息
			msgService.sendMsg(msgList);

			// 飞书消息,目前只针对592800租户发送
			final String fixedTenantId = "592800";
			if (msgList.stream().anyMatch(t -> Func.equalsSafe(fixedTenantId, t.getTenantId()))) {
				List<UserCertVO> expireSoonList = list.stream().filter(t -> t.getStatus() == CertStatusEnum.EXPIRING_SOON.getId() && Func.equalsSafe(fixedTenantId, t.getTenantId())).collect(Collectors.toList());
				if (Func.isNotEmpty(expireSoonList)) {
					String feishuContent = String.format("%s,将有%d位人员【%s】即将到期，请尽快通知换证",
						DateUtil.format(DateUtil.date(), DatePattern.CHINESE_DATE_PATTERN), expireSoonList.size(), expireSoonList.get(0).getCertName());
					// 飞书发送通知卡片给管理员
					String appId = feiShuConfiguration.getClitSecure(FeishuClientEnum.CERT).getAppId();
					FeiShuCertContentTemplate feiShuCertContentTemplate = new FeiShuCertContentTemplate(appId);
					String certContentTemplate = feiShuCertContentTemplate.getCertContentTemplate();
					String certContentTemplateFormat = String.format(certContentTemplate, feishuContent);
					userCertService.sendMsgToAdministrator(certContentTemplateFormat);
				}
			}
		}
		XxlJobHelper.handleSuccess("证件到期提醒任务-【执行】成功");
	}
}
